import logging
from typing import Optional
from fastapi import APIRouter, Depends, Query, Path
from pydantic import BaseModel, Field
from sqlalchemy import text
from sqlalchemy.engine import create
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy.orm import Session

from commons.BaseResponse import BaseResponse
from commons.PaginationBase import PaginationBase
from datebase import get_db
from utils.EncryptionUtil import oauth2_scheme, EncryptionMiddleware

fault_danger_router = APIRouter(prefix="/fault/faultDanger", tags=["紧急程度管理"],
                                dependencies=[Depends(oauth2_scheme)])


class FaultDangerSearch(PaginationBase):
    furgentname: str = Field("", description="紧急程度名")


@fault_danger_router.get("/list", summary="紧急程度查询接口")
def list_fault(search: FaultDangerSearch = Query(), db: Session = Depends(get_db)):
    param = {}
    sql = "select count(1) from s_ts_fault_danger where 1=1"
    if search.furgentname != "":
        sql = sql + " and furgentname like concat('%', :furgentname ,'%')"
        param["furgentname"] = search.furgentname
    count = db.execute(text(sql), param).scalar()

    param = {}
    sql = "select furgentno,furgentname,fupddate,foperator"
    sql = sql + " from s_ts_fault_danger where 1=1"
    if search.furgentname != "":
        sql = sql + " and furgentname like concat('%', :furgentname ,'%')"
        param["furgentname"] = search.furgentname
    if search.order == "desc":
        sql = sql + " order by  furgentno desc "
    else:
        sql = sql + " order by  furgentno "
    sql = sql + " limit :limit offset :offset "
    param["offset"] = search.offset
    param["limit"] = search.limit
    data = db.execute(text(sql), param).fetchall()

    data_list = []
    for key in range(len(data)):
        d1 = {}
        d1['furgentno'] = data[key][0]
        d1['furgentname'] = data[key][1]
        d1['fupddate'] = data[key][2]
        d1['foperator'] = data[key][3]
        data_list.append(d1)

    info_dict = {"list": data_list, "limit": search.limit, "page": search.pageIndex,
                 "pages": (count + search.limit - 1) // search.limit,
                 "total": count}
    return BaseResponse.success(data=info_dict)


class UrgencyCreate(BaseModel):
    """紧急程度新增请求参数"""
    furgentno: str = Field(..., description="紧急程度编号（唯一标识）")
    furgentname: str = Field(..., description="紧急程度名称")
    foperator: str = Field(..., description="操作人")
    fupddate: str = Field(..., description="更新日期(yyyy-MM-dd HH:mm:ss)")


@fault_danger_router.post("/create", summary="紧急程度新增接口")
def create_fault(create: UrgencyCreate, db: Session = Depends(get_db)):
    try:
        with db.begin():
            sql = "select furgentno from s_ts_fault_danger where furgentno= :furgentno "
            data = db.execute(text(sql), {"furgentno": create.furgentno}).fetchall()

            if len(data) > 0:
                return BaseResponse.success(data=data)
            else:
                sql = "insert into s_ts_fault_danger(furgentno,furgentname,fupddate,foperator)"
                sql = sql + " values( :furgentno , :furgentname , :fupddate , :foperator );"
                db.execute(text(sql), {
                    "furgentno": create.furgentno,
                    "furgentname": create.furgentname,
                    "fupddate": create.fupddate,
                    "foperator": create.foperator,
                })
                # 返回
                data = {
                    "furgentno": create.furgentno
                    , "furgentname": create.furgentname
                    , "fupddate": create.fupddate
                    , "foperator": create.foperator
                }
                return BaseResponse.success(data=data)
    except SQLAlchemyError as e:
        # 发生异常时自动回滚
        db.rollback()
        # 记录错误日志
        logging.error(f"数据库错误: {str(e)}")
        # 返回错误响应
        return BaseResponse.error(message="数据库操作失败")
    except Exception as e:
        db.rollback()
        logging.error(f"未知错误: {str(e)}")
        return BaseResponse.error(message="令牌过期")


@fault_danger_router.post("/update", summary="紧急程度修改接口")
def update_fault(update: UrgencyCreate, db: Session = Depends(get_db)):
    try:
        with db.begin():
            sql = "update s_ts_fault_danger"
            sql = sql + " set furgentname= :furgentname "
            sql = sql + ",fupddate= :fupddate ,foperator= :foperator "
            sql = sql + " where furgentno= :furgentno "
            db.execute(text(sql), {
                "furgentname": update.furgentname,
                "fupddate": update.fupddate,
                "foperator": update.foperator,
                "furgentno": update.furgentno
            })
            return BaseResponse.success()
    except SQLAlchemyError as e:
        # 发生异常时自动回滚
        db.rollback()
        # 记录错误日志
        logging.error(f"数据库错误: {str(e)}")
        # 返回错误响应
        return BaseResponse.error(message="数据库操作失败")
    except Exception as e:
        db.rollback()
        logging.error(f"未知错误: {str(e)}")
        return BaseResponse.error(message="令牌过期")


@fault_danger_router.post("/delete/{furgentno}", summary="紧急程度删除接口")
def delete_fault(furgentno: str = Path(description="紧急程度删除接口"), db: Session = Depends(get_db)):
    try:
        with db.begin():
            sql = "delete from s_ts_fault_danger where furgentno= :furgentno "
            db.execute(text(sql), {
                "furgentno": furgentno
            })
    except SQLAlchemyError as e:
        # 发生异常时自动回滚
        db.rollback()
        # 记录错误日志
        logging.error(f"数据库错误: {str(e)}")
        # 返回错误响应
        return BaseResponse.error(message="数据库操作失败")
    except Exception as e:
        db.rollback()
        logging.error(f"未知错误: {str(e)}")
        return BaseResponse.error(message="令牌过期")
